import React, { useState, useEffect, useRef } from "react"
import "./Classfig.scss"
import { getRankCategoryList } from "../../services/index"
import { CategoryItem } from "../../utils/interface"
import {useHistory} from "react-router-dom"
const Classfig: React.FC = () => {
    let [CategoryList, setCategoryList] = useState<CategoryItem[]>([])
    let [carIndex, setCarIndex] = useState(0)
    let addRef = useRef(null)
    let history = useHistory()
    useEffect(() => {
        getRankCategoryList().then(res => {
            setCategoryList(res.data.dataList)
        });
    }, [])
    function changeIndex(index: number) {
        setCarIndex(index)
        let h2s = document.querySelectorAll("h2");
        (addRef as React.MutableRefObject<any>).current.scrollTop = h2s[index].offsetTop - 50
    }
    function toScroll() {
        let h2s = document.querySelectorAll("h2");
        h2s.forEach((item, index) => {
            if (item.getBoundingClientRect().top - 50 < 1) {
                setCarIndex(index)
            }
        })
    }
    return <div className="classfig">
        <section className="ipt">
            <div className="box" onClick={()=>history.push("/search")}><span>搜索你喜欢的内容</span></div>
        </section>
        <section className="main">
            <div className="navLeft" ref={addRef}>
                {
                    CategoryList.map((item, index) => {
                        return <span key={index} className={carIndex === index ? "actives" : ""} onClick={() => { changeIndex(index) }}>{item.name}</span>
                    })
                }
            </div>
            <div className="navRight" ref={addRef} onScroll={toScroll}>
                {
                    CategoryList.map((item, index) => {
                        return <div key={index}>
                            <h2>{item.name}</h2>
                            <div>
                                {
                                    item.rankList.map((item) => {
                                        return <div key={item.name}>
                                            <h3><img src={item.image} alt="" /></h3>
                                            <span>{item.name}</span>
                                        </div>
                                    })
                                }
                            </div>
                        </div>
                    })
                }
            </div>
        </section>
    </div>
}
export default Classfig